import { create } from "zustand";
import { immer } from "zustand/middleware/immer";
import { devtools, persist, createJSONStorage } from "zustand/middleware";
import axios from "axios";

const URL = "http://localhost:3001/takeaway";

export const useCategoryStore = create(
  immer(
    devtools(
      persist(
        (set, get) => ({
          // 商品列表
          categoryList: [],
          // 菜单激活
          activeIndex: 0,
          // 购物车列表
          cartList: []
        }),
        {
          name: "categoryStore",
          partialize: (state) => ({ activeIndex: state.activeIndex }),
          storage: createJSONStorage(() => sessionStorage)
        }
      ),
      { enabled: true, name: "Category Store" }
    )
  )
);

export const setCategoryList = async () => {
  const res = await axios.get(URL);
  useCategoryStore.setState((state) => {
    state.categoryList = res.data;
    console.log(state.categoryList);
  });
};

// 更改activeIndex的值
export const changeActiveIndex = (index) => {
  useCategoryStore.setState((state) => {
    state.activeIndex = index;
    console.log(state.activeIndex);
  });
};

// 添加购物车
export const addCart = (item) => {
  // 使用useCategoryStore的setState方法，更新购物车状态
  useCategoryStore.setState((state) => {
    // 查找购物车中是否存在当前添加的商品，如果存在，则数量加1，否则添加到购物车中
    const cartItem = state.cartList.find((i) => i.name === item.name);
    if (cartItem) {
      cartItem.count++;
    } else {
      state.cartList.push({ ...item, count: 1 });
      console.log(state.cartList);
    }
  });
};
